﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

namespace Com.Core.Helps
{
    public enum ImageExtension
    {
        Jpg = 255,
        Gif = 71,
        Png = 137
    }

    #region 变量声明开始  
    /// <summary>  
    /// 枚举: 水印位置  
    /// </summary>  
    public enum WatermarkPosition
    {
        /// <summary>  
        /// 左上  
        /// </summary>  
        LeftTop,
        /// <summary>  
        /// 左中  
        /// </summary>  
        Left,
        /// <summary>  
        /// 左下  
        /// </summary>  
        LeftBottom,
        /// <summary>  
        /// 正上  
        /// </summary>  
        Top,
        /// <summary>  
        /// 正中  
        /// </summary>  
        Center,
        /// <summary>  
        /// 正下  
        /// </summary>  
        Bottom,
        /// <summary>  
        /// 右上  
        /// </summary>  
        RightTop,
        /// <summary>  
        /// 右中  
        /// </summary>  
        RightCenter,
        /// <summary>  
        /// 右下  
        /// </summary>  
        RigthBottom
    }
    #endregion 变量声明结束  

    public class ImageHelper
    {
        public static void DeleteImage(string filePath)
        {
            if (!string.IsNullOrEmpty(filePath))
            {
                filePath = HttpContext.Current.Server.MapPath(filePath);
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }
        }

        public static void DeleteImages(string[] filePathes)
        {
            foreach (var filePaht in filePathes)
            {
                DeleteImage(filePaht);
            }
        }

        /// <summary>
        /// 打图片水印
        /// </summary>
        /// <param name="path">原图片</param>
        /// <param name="pathSyp">生成后图片地址</param>
        /// <param name="pathSypf">水印图片地址</param>
        public static void AddWaterPic(string path, string pathSyp, string pathSypf)
        {
            Image image = Image.FromFile(path);
            Image copyImage = Image.FromFile(pathSypf);
            Graphics g = Graphics.FromImage(image);
            g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
            g.Dispose();

            image.Save(pathSyp);
            image.Dispose();

            if (path.Equals(pathSyp))
            {
                File.Delete(pathSyp);
            }
        }

        /// <summary>   
        /// 给图片上水印   
        /// </summary>   
        /// <param name="filePath">原图片地址</param>   
        /// <param name="waterFile">水印图片地址</param>   
        public static void MarkWater(string filePath, string waterFile)
        {
            //GIF不水印   
            int i = filePath.LastIndexOf(".");
            string ex = filePath.Substring(i, filePath.Length - i);
            if (string.Compare(ex, ".gif", true) == 0)
            {
                return;
            }

            string ModifyImagePath =  filePath;//修改的图像路径   
            int lucencyPercent = 25;
            Image modifyImage = null;
            Image drawedImage = null;
            Graphics g = null;
            try
            {
                //建立图形对象   
                modifyImage = Image.FromFile(ModifyImagePath, true);
                drawedImage = Image.FromFile(waterFile, true);
                g = Graphics.FromImage(modifyImage);
                //获取要绘制图形坐标   
                int x = modifyImage.Width - drawedImage.Width;
                int y = modifyImage.Height - drawedImage.Height;
                //设置颜色矩阵   
                float[][] matrixItems ={
            new float[] {1, 0, 0, 0, 0},
            new float[] {0, 1, 0, 0, 0},
            new float[] {0, 0, 1, 0, 0},
            new[] {0, 0, 0, lucencyPercent/100f, 0},
            new float[] {0, 0, 0, 0, 1}};

                ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
                ImageAttributes imgAttr = new ImageAttributes();
                imgAttr.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                //绘制阴影图像   
                g.DrawImage(drawedImage, new Rectangle(x, y, drawedImage.Width, drawedImage.Height), 10, 10, drawedImage.Width, drawedImage.Height, GraphicsUnit.Pixel, imgAttr);
                //保存文件   
                string[] allowImageType = { ".jpg", ".gif", ".png", ".bmp", ".tiff", ".wmf", ".ico" };
                FileInfo fi = new FileInfo(ModifyImagePath);
                ImageFormat imageType = ImageFormat.Gif;
                switch (fi.Extension.ToLower())
                {
                    case ".jpg": imageType = ImageFormat.Jpeg; break;
                    case ".gif": imageType = ImageFormat.Gif; break;
                    case ".png": imageType = ImageFormat.Png; break;
                    case ".bmp": imageType = ImageFormat.Bmp; break;
                    case ".tif": imageType = ImageFormat.Tiff; break;
                    case ".wmf": imageType = ImageFormat.Wmf; break;
                    case ".ico": imageType = ImageFormat.Icon; break;
                    default: break;
                }
                MemoryStream ms = new MemoryStream();
                modifyImage.Save(ms, imageType);
                byte[] imgData = ms.ToArray();
                modifyImage.Dispose();
                drawedImage.Dispose();
                g.Dispose();
                FileStream fs = null;
                File.Delete(ModifyImagePath);
                fs = new FileStream(ModifyImagePath, FileMode.Create, FileAccess.Write);
                if (fs != null)
                {
                    fs.Write(imgData, 0, imgData.Length);
                    fs.Close();
                }
            }
            finally
            {
                try
                {
                    drawedImage.Dispose();
                    modifyImage.Dispose();
                    g.Dispose();
                }
                catch
                {
                }
            }
        }

        public static string GetPic(string pic,int identityNumber)
        {
            if (File.Exists(HttpContext.Current.Server.MapPath(pic)))
            {
                var folder = $"/UploadFile/Users/{identityNumber}/{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.Now.Day}/";
                if (!Directory.Exists(HttpContext.Current.Server.MapPath(folder))) Directory.CreateDirectory(HttpContext.Current.Server.MapPath(folder));
                string fName = pic.Split('/')[pic.Split('/').Length - 1];
                File.Copy(HttpContext.Current.Server.MapPath(pic), HttpContext.Current.Server.MapPath($"{folder}{fName}"), true);
                File.Delete(HttpContext.Current.Server.MapPath(pic));
                pic = $"{folder}{fName}";
            }
            else
            {
                pic = null;
            }
            return pic;
        }

        /// <summary>
        /// 检查图片格式
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static bool CheckExtension(byte[] bytes)
        {
            MemoryStream ms = new MemoryStream(bytes);
            BinaryReader br = new BinaryReader(ms);
            bool flag = false;
            try
            {
                var buffer = br.ReadByte();
                var fileclass = buffer.ToString();
                var temp = int.Parse(fileclass);
                var t = Enum.IsDefined(typeof(ImageExtension), temp);
                if (t) flag = true;
            }
            catch
            {
                flag = false;
            }
            finally
            {
                ms.Close();
                br.Close();
            }
            return flag;
        }
    }
}
